package com.softeware.service.impl;

import com.softeware.dao.BaseDao;
import com.softeware.dao.user.UserDao;
import com.softeware.dao.user.UserDaoImpl;
import com.softeware.pojo.UserInfo;
import com.softeware.service.UserService;
import jakarta.servlet.ServletContext;

import java.io.IOException;
import java.sql.Connection;

public class UserServiceImpl implements UserService {
    private UserDao userDao;

    public UserServiceImpl(ServletContext application) {
        this.userDao = new UserDaoImpl();
    }

    @Override
    public UserInfo login(String username,String password) throws IOException {
        Connection connection = null;
        UserInfo user = null;
        try{
            connection = BaseDao.getConnection();
            user = userDao.getLoginUser(connection,username);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            BaseDao.closeResource(connection,null,null);
        }
        if(user!=null){
            if(user.getPassword().equals(password)==false){
                user=null;
            }
        }
        return user;
    }

    @Override
    public boolean register(UserInfo user){
        boolean flag = false;
        Connection connection = null;
        try{
            connection = BaseDao.getConnection();
            int updateRows = userDao.add(connection,user);
//            connection.commit();
            if(updateRows>0){
                flag=true;
                System.out.println("add success!");
            }
            else{
                System.out.println("add failed!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            BaseDao.closeResource(connection,null,null);
        }
        return flag;
    }
}
